import datetime
import json
import random
import time
from flask import Blueprint, request, jsonify, redirect

from Laboratory.db import db
from Laboratory.util.comm import get_ali_object
from Laboratory.util.myredis import r

vip_blue = Blueprint("vip", __name__)

# 购买vip生成订单
@vip_blue.route("/order", methods=["POST"])
def order():
    data = json.loads(request.data)
    user_id = data['user_id']
    year = data['year']
    money = 200
    # 生成订单
    tmoney = money * int(year)
    order_no = str(int(time.time())) + str(user_id) + str(random.randint(100, 999))
    sql = "insert into vip_record(order_on, userid, year, money, active_money, status) values ('%s', %d, %d, %f, %f, 1)" % (order_no, int(user_id), year, tmoney, tmoney)
    db.add(sql)
    db.commit()
    pay = get_ali_object()
    query_params = pay.direct_pay(
        subject='test',  # "充值服务",  # 商品简单描述
        out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(1.00),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({'code': 200, 'url': pay_url})

def updateorders(out_trade_no,trade_no):
    # 加事务处理
    # 更新订单状态
    try:
        stime = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
        sql = "update vip_record set status=2,update_time='%s',order_on='%s' where id=%d" % (stime, trade_no, int(out_trade_no))
        db.add(sql)
        # 更新会员状态
        # 查询订单对应的用户
        sql1 = "select userid from vip_record where id=%d"%int(out_trade_no)
        user = db.findOne(sql1)
        usql = "update user set level=2 where id=%d"%(int(user['user_id']))
        db.add(usql)
        #从队列中删除
        r.sortedset_delete('orderpayfail')
        db.commit()
    except:
        db.rollback()

@vip_blue.route("/callback")
def callback():
    trade_no = request.args.get('trade_no') #流水号
    out_trade_no = request.args.get('out_trade_no') #订单号
    updateorders(out_trade_no, trade_no)
    # 跳转到个人中心页面 我的订单页面
    return redirect("http://localhost:8080/#/")

# 获取标签全部数据
def get_label():
    # 获取reds中的数据
    res = r.str_get('tags')
    if res:
        res = json.loads(res)
        print('缓存')
    else:
        sql = "select * from tags"
        res = db.findAll(sql)
        print('数据库')
        # 把数据加入redis中
        r.str_add('tags', json.dumps(res))
    return res

# 获取课程全部数据
def get_courses(page):
    # 获取类别全部数据
    page_size = 2
    # 查询缓存如果存在直接返回
    key = "home" + str(page)
    clist = r.str_get(key)
    if clist:
        courselist = json.loads(clist)
    else:
        # 获取指定页数据
        start = (int(page) - 1) * page_size
        # 并发访问同时操作数据库，解决方案分布式锁  setnx  setnx  a  2
        flag = r.str_setnx(key + "setnx", 1)
        if flag == True:
            sql1 = "select * from courses limit %d,%d" % (int(start), page_size)
            courselist = db.findAll(sql1)
            # 存在redis  decimal float  datetime 时间日期类型
            list = []
            for i in courselist:
                t = datetime.datetime.strftime(i['add_time'], "%Y-%m-%d %H:%M:%S")
                i['price'] = float(i['price'])
                i['add_time'] = t
                list.append(i)
            r.str_add(key, json.dumps(list))
            # 释放锁
            r.del_key(key + "setnx")

    # 获取共有多少条记录
    sql = "select count(id) as t from courses"
    res = db.findone(sql)
    total = res['t']
    # 指定每页显示多少条

    return courselist, total, page_size



def get_categorie():
    sql = "select * from ctype"
    res = db.findAll(sql)
    return res

@vip_blue.route("/getCourse")
def home():
    # 获取当前页面
    page = request.args.get("page")
    # 获取查询条件
    typeid = request.args.get("type")
    tagid = request.args.get("tagid")
    online = request.args.get("online")
    # 排序条件
    orderbyid = request.args.get("orderbyid")

    where = ""
    if int(typeid) > 0:
        where = where + " and c.type=" + typeid

    if int(online) > 0:
        where = where + " and c.online=" + online

    if int(tagid) > 0:
        tsql = "select count(c.id) as tcount from courses as c inner join course_tag as cl on cl.courseid=c.id  where cl.tagid=" + tagid
        sql = "select * from courses as c inner join course_tag as cl on cl.courseid=c.id  where cl.tagid=" + tagid
    else:
        sql = "select * from courses as c  where 1=1"
        tsql = "select count(c.id) as  tcount   from courses as c  where 1=1"

    if where:
        sql = sql + " " + where
        tsql = tsql + " " + where

    if int(orderbyid) > 0:
        if int(orderbyid) == 1:
            sql = sql + " order by c.id desc"
        else:
            sql = sql + " order by c.click_num desc"

    # 查询总共有多少条
    res = db.findOne(tsql)
    total = res['tcount']
    page_size = 2
    start = (int(page) - 1) * page_size
    sql = sql + " limit %d,%d" % (start, page_size)
    courselist = db.findAll(sql)
    # 标签
    taglist = get_label()
    # 课程
    # courselist, total, page_size = get_courses(page)
    # 类别
    typelist = get_categorie()
    return jsonify({
        "code": 200,
        "taglist": taglist,
        "typelist": typelist,
        "courselist": courselist,
        "total": total,
        "page_size": page_size
    })


